package lwk.juc.sup;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @author:lwk
 * @create: 2022-08-16 20:17
 * @Description:
 */
public class SemaphoreDemo {
    public static void main(String[] args) {

        // 限流
        Semaphore semaphore = new Semaphore(3);

        for (int i = 1; i <= 6; i++) {
            new Thread(()->{
                try {
                    // 获取，假设已经满了，等待，等待被释放为止
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName()+"抢到车位");
                    TimeUnit.SECONDS.sleep(1);
                    System.out.println(Thread.currentThread().getName()+"离开车位");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    // 释放，会将当前的信号量+1，然后唤醒等待的线程
                    semaphore.release();
                }

            },String.valueOf(i)).start();

        }

    }
}
